/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import dk.redia.lib.log.Log;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.StringUtils;
import dk.redia.libraryapp.activityutils.LibraryAppActivity;
import dk.redia.libraryapp.adapters.AdapterStateListener;
import dk.redia.libraryapp.adapters.SearchResultAdapter;
import dk.redia.libraryapp.model.Reservation;
import dk.redia.libraryapp.model.SearchResultDataItem;
import dk.redia.libraryapp.net.SearchResultsRemoteListManager;
import dk.redia.libraryapp.search.QueryManager;
import dk.redia.libraryapp.utils.SoftKeyboardUtils;

public class SearchResultActivity extends LibraryAppActivity implements AdapterStateListener, OnItemSelectedListener {

	private static final String logTag = "SearchResultActivity";
	private ArrayAdapter<String> facetsSpinnerAdapter;
	private SearchResultAdapter searchResultAdapter;
	private boolean ignoreNextFacetSelection;
	private ProgressDialog progressDialog;
	private String currentFacetText = "Alle";
	private String currentFacet;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.searchresult);

	    facetsSpinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item) {
	    	
	    	@Override
	    	public View getDropDownView(int position, View convertView, ViewGroup parent) {
	    		
	    		// This gets called when the system needs a view
	    		// for use in the expanded spinner
	    		
	    		TextView tv;
	    		
	    		if (convertView==null) {
	    			LayoutInflater inflater = (LayoutInflater)SearchResultActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);	    			
	    			tv = (TextView)inflater.inflate(R.layout.materialcategoryspinneritem, null);
	    		} else {
	    			tv = (TextView)convertView;
	    		}	    		

	    		@SuppressWarnings("unchecked")
				Map<String, Integer> facetMap = (Map<String, Integer>)searchResultAdapter.getExtraResultData(SearchResultsRemoteListManager.EXTRA_RESULT_DATA_KEY_FACET_MAP);
	    		String facet = this.getItem(position);
	    		Integer count = facetMap.get(facet);
	    		if (facet.equals("")) {
					facet = "Alle";
				}
				String facetText = StringUtils.firstToUpperCase(facet) + (count==null ? "" : " (" + count + ")");
	    		
	    		tv.setText(facetText);
	    		tv.setTag(facet);
	    			    		
	    		return tv;
	    		
	    	}
	    	
	    	public View getView(int position, View convertView, ViewGroup parent) {

	    		// This gets called when the system needs a view
	    		// for use in the collapsed spinner
	    		RelativeLayout rl;
	    		
	    		if (convertView==null) {
	    			LayoutInflater inflater = (LayoutInflater)SearchResultActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);	    			
	    			rl = (RelativeLayout)inflater.inflate(R.layout.materialcategoryspinnercollapseditem, null);
	    		} else {
	    			rl = (RelativeLayout)convertView;
	    		}
	    		
	    		TextView tv = (TextView)rl.findViewById(R.id.materialCategorySpinnerCollapsedItemTextView);
				//Map<String, Integer> facetMap = (Map<String, Integer>)searchResultAdapter.getExtraResultData(SearchResultsRemoteListManager.EXTRA_RESULT_DATA_KEY_FACET_MAP);
	    		//String facet = this.getItem(position);

				String facetText = currentFacetText;
				String facet = currentFacet;
				
				if (currentFacet==null || currentFacetText.length()==0) {
					facet = "";
				}
				
	    		if (currentFacetText==null || currentFacetText.length()==0) {
					facetText = "Alle";
				}

	    		
	    		tv.setText(facetText);
	    		tv.setTag(facet);
	    		rl.setTag(facet);
	    		return rl;
	    	}
	    };
	    facetsSpinnerAdapter.setDropDownViewResource(R.layout.materialcategoryspinneritem);
//	    facetsSpinnerAdapter.add("Test 123");
//	    facetsSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    Spinner facetsSpinner = (Spinner)findViewById(R.id.searchResultFacetsSpinner);
	    facetsSpinner.setOnItemSelectedListener(this);
	    facetsSpinner.setAdapter(facetsSpinnerAdapter);
	    ListView lv = (ListView)findViewById(R.id.searchResultListView);
	    searchResultAdapter = new SearchResultAdapter(this);
	    searchResultAdapter.addAdapterSizeListener(this);
	    ignoreNextFacetSelection = true;
	    lv.setAdapter(searchResultAdapter);
	    
	    search(QueryManager.getInstance().getSearchQuery(), "");
	}
	
	private void search(String query, String contentCategory) {
		if (query.trim().equals("")) {
			AppApplication.toast(R.string.searchResultNoQueryText, Toast.LENGTH_LONG);
		} else {
			// Avoid leaking dialogs if this gets called
			// twice before we get around to closing the dialog below
			if (progressDialog !=null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			progressDialog = ProgressDialog.show(
			    		this, 
			    		getString(R.string.searchProgressTitleText), 
			    		getString(R.string.searchProgressBodyText), 
			    		true);
//			ignoreNextFacetSelection = true;
//			facetsSpinnerAdapter.clear();
//			((Spinner)findViewById(R.id.searchResultFacetsSpinner)).removeAllViews();
			searchResultAdapter.search(query, contentCategory);
		}
	}
	
	private void destroyProgressDialog() {
		if (progressDialog!=null) {
			progressDialog.dismiss();
		}
		progressDialog = null;
	}
	
	public void onPause() {
		super.onPause();
		destroyProgressDialog();
	}
	
	public void onStop() {
		super.onStop();
		destroyProgressDialog();
	}
	
	public void onDestroy() {
		super.onDestroy();
		destroyProgressDialog();
	}
	
	public void onSearchResultItemClicked(View v) {
		Log.d(SearchResultActivity.logTag, "Search result item clicked");
		SearchResultDataItem srdi = (SearchResultDataItem)v.getTag();
		Intent intent = new Intent(this, SearchResultDetailsActivity.class);
		intent.putExtra(SearchResultDetailsActivity.extraKeySearchResultDataItem, srdi);
		startActivity(intent);
	}
	
	public void onReserveButtonClicked(View v) {
		Log.d(logTag, "Reserve button clicked");
//		searchResultAdapter.reserve((String)v.getTag();
//		Object o = v.getTag();
		Intent intent = new Intent(this, AuthenticateActivity.class);
		intent.putExtra(AuthenticateActivity.EXTRAS_KEY_CALLBACK_CLASS, ReservationResultActivity.class);
		intent.putExtra(ReservationResultActivity.EXTRAS_KEY_RESERVATION, (Reservation)v.getTag());
		this.startActivity(intent);

	}

	public void dataSetSizeChanged(int length) {
		findViewById(R.id.searchResultListView).setVisibility(View.VISIBLE);
		TextView resultCountTextView = (TextView)findViewById(R.id.searchResultResultCountTextView);
		Spinner facetsSpinner = (Spinner)findViewById(R.id.searchResultFacetsSpinner);
		facetsSpinner.setSelection(0);
		facetsSpinnerAdapter.clear();
		resultCountTextView.setText("(" + length + ")");
		
		@SuppressWarnings("unchecked")
		Map<String, Integer> facetMap = (Map<String, Integer>)searchResultAdapter.getExtraResultData(SearchResultsRemoteListManager.EXTRA_RESULT_DATA_KEY_FACET_MAP);
//		ignoreNextFacetSelection = true;
		if (facetMap!=null) {
			facetsSpinnerAdapter.clear();
//			LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
			// We need the "" facet to come first, as that means all results
			// and should be the default
			if (facetMap.containsKey("")) {
				facetMap.remove("");
			}
			facetsSpinnerAdapter.add("");
			List<String> facetList = new ArrayList<String>(facetMap.keySet());
			Collections.sort(facetList);
//			facetMap.keySet()
			for (String facet : facetList) {
//				TextView facetTextView = (TextView)inflater.inflate(R.layout.materialcategoryspinneritem, null);
//				TextView facetTextView = new TextView(this);
//				facetTextView.setLayoutParams(layoutParams);
//				facetTextView.setTag(facet);
				//if (facet.equals("")) {
				//	facet = "Alle";
				//}
//				String facetText = StringUtils.firstToUpperCase(facet) + " (" + facetMap.get(facet) + ")";
//				facetTextView.setText(facetText);
				facetsSpinnerAdapter.add(facet);
			}
			int currentFacetPosition = facetsSpinnerAdapter.getPosition(currentFacet);
			facetsSpinner.setSelection(currentFacetPosition);
			facetsSpinner.setEnabled(true);
		} else {
			facetsSpinner.setEnabled(false);
		}
	}

	public void onItemSelected(AdapterView<?> arg0, View selectedView, int arg2, long arg3) {
		if (ignoreNextFacetSelection) {
			ignoreNextFacetSelection = false;
			return;
		}
		String facet = facetsSpinnerAdapter.getItem(arg2);
//		if (!(selectedView instanceof TextView)) {
//			Log.d(logTag, "Received onItemSelected with selected view of type " + selectedView.getClass());
//			return;
//		}
//		String facet = (String)selectedView.getTag();
		currentFacetText = StringUtils.firstToUpperCase(facet);
		currentFacet = facet;

		Log.d(logTag, "Selected content type " + facet);
		search(QueryManager.getInstance().getSearchQuery(), facet);
	}

	public void onSpinnerTextViewClicked(View v) {
		((Spinner)findViewById(R.id.searchResultFacetsSpinner)).performClick();
	}
	
	public void onNothingSelected(AdapterView<?> arg0) {
		// Intentionally do nothing
	}

	@Override
	public void onSearchButtonClick(View button) {
		EditText et = (EditText)findViewById(R.id.searchBarEditText);
		SoftKeyboardUtils.hideSoftKeyboard(et);
		QueryManager.getInstance().setSearchQuery(et.getText().toString());
		currentFacet = "";
		search(QueryManager.getInstance().getSearchQuery(), "");
	}

	public void chunkLoaded(int offset, int count) {
		if (progressDialog!=null && progressDialog.isShowing()) {
			progressDialog.hide();
		}
		
		if (searchResultAdapter.getCount()==0) {
			AppApplication.toast(R.string.searchResultNoResults, Toast.LENGTH_LONG);
		}
	}

	public void chunkLoadFailed(int offset, int count, String message) {
		if (progressDialog!=null && progressDialog.isShowing()) {
			progressDialog.hide();
		}
		AppApplication.toast(String.format(getString(R.string.chunkLoadFailedText), message), Toast.LENGTH_SHORT);
	}
}
